package com.gmail.ceac13;

import java.util.List;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class ConnectMEService extends Service implements ConnectMEServiceActions, LocationListener {
	boolean ativo;
	protected int count;
	private final IBinder conexao = new LocalBinder();
	private double latitude;
	private double longitude;
	private static final long[] minutos = {60000,300000,600000,1800000,3600000};
	private boolean gpsAtivo = true;
	private PrincipalAdapter adapter;
	
	protected static final int ATUALIZAR_LISTA = 1;
	private Handler handler = new MyHandler();
	
	public class LocalBinder extends Binder {
		public ConnectMEServiceActions getActions() {
			return ConnectMEService.this;
		}
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return conexao;
	}
	
	public void teste() {
		Log.i("livro", "Chegou aqui");
	}
	
	@Override
	public void onCreate() {
		Log.i("livro", "ConnectMEService.onCreate()");
		ativo = true;
		count = 0;
		getLocationManager().requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		Location l = getLocationManager().getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (l != null) {
			longitude = l.getLongitude();
			latitude = l.getLatitude();
		}
		Message msg = new Message();
		msg.what = ATUALIZAR_LISTA;
		handler.sendMessageDelayed(msg, 10000);
	}
	
	private LocationManager getLocationManager() {
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		return locationManager;
	}
	
	public void onStart() {
		Log.i("livro", "ConnectMEService.onStart()");
	}
	
	@Override
	public void onDestroy() {
		Log.i("livro", "ConnectMEService.onDestroy()");
		getLocationManager().removeUpdates(this);
		ativo = false;
	}

	@Override
	public int count() {
		count++;
		return count;
	}
	@Override
	public void atualiza() {
		Log.i("ConnectME","1");
		SharedPreferences settings = getSharedPreferences("ConnectMe",MODE_PRIVATE);
		if (gpsAtivo) {
			Log.i("ConnectME","2");
	        int user_id = settings.getInt("user_id", -1);
	        String posicao = getPosicao();
	        Log.i("ConnectME","3");
	        if (!(latitude == 0 && longitude == 0)) {
	        	List <Friend> amigos;
	        	
		    	String endServer = settings.getString("servidor", "http://connectme.scienceontheweb.net/");
		    	//String endServer = settings.getString("servidor", "http://10.0.2.2/connectme/");
	            amigos = Servidor.listarAmigos(user_id, posicao, endServer);
	
	            FriendDao dao = new FriendDao(this);
	            dao.syncronizerFriend(amigos);
	            Log.i("ConnectME","4");
	            if (adapter != null) {
	            	adapter.atualizarAdapter();
	            	adapter.notifyDataSetChanged();
	            }
	            Log.i("ConnectME","5");
	        }
		}
	}
	
	@Override
	public void atualizarAmigos() {
		atualiza();
		SharedPreferences settings = getSharedPreferences("ConnectMe",MODE_PRIVATE);
		Message msg = new Message();
		msg.what = ATUALIZAR_LISTA;
		handler.sendMessageDelayed(msg, minutos[settings.getInt("tempo", 0)]);
	}

	@Override
	public String getPosicao() {
		return this.latitude + "," + this.longitude;
		
	}
	
	@Override
	public void onLocationChanged(Location location) {
		this.latitude = location.getLatitude();
		this.longitude = location.getLongitude();
	}

	@Override
	public void onProviderDisabled(String arg0) {
		Toast t = Toast.makeText(this, "Ative o GPS para o funcionamento correto do ConnectME.", Toast.LENGTH_LONG);
		t.show();
		gpsAtivo = false;
	}

	@Override
	public void onProviderEnabled(String arg0) {
		gpsAtivo = true;
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
	}

	@Override
	public void setAdapter(PrincipalAdapter adaptador) {
		this.adapter = adaptador;
	}
	
	private class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case ATUALIZAR_LISTA:
				if (ativo)
					atualizarAmigos();
				break;
			}
		}
	}
	@Override
	public void setAtivo(boolean b) {
		this.ativo = b;
		
	}
}
